package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.AreaBiz;
import com.useeinfo.oa.modules.base.entity.Area;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Auther: 陈炜
 * @Date: 2018/12/11 13:03
 * @Description: 设备分类action
 */
@Controller
@RequestMapping("/web/admin/area")
public class AreaManageAction {
    @Autowired
    private AreaBiz areaBiz;

    @RequestMapping("/list")
    public ModelAndView list(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/area/areaList");

        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "parentCode", required = false) String parentCode,//tree参数
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {
        JSONObject result = new JSONObject();
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        queryParam.getSqlMap().put("searchCode", searchCode);
        if(StringUtils.isNotBlank(parentCode)){
            queryParam.getSqlMap().put("parentId", parentCode);
        }else{
            queryParam.getSqlMap().put("bigParent","0");
        }
        if(StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        result = areaBiz.findJSONList(queryParam);
        JSONArray rows = result.getJSONArray("list");
        for (int i = 0; i < rows.size(); i++) {
            JSONObject json = rows.getJSONObject(i);
            //查出tree展示参数
            json.put("treeLevel",json.getInteger("lvl")==null?0:json.getIntValue("lvl"));
            json.put("isTreeLeaf",!areaBiz.existHaveSon(json.getLong("id")));
            json.put("parentCode",json.getInteger("parentId")+"");//不加这个parentCode展开后就会缩不回去
            json.put("isRoot",true);
        }
        return result;
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise",enterprise);
        Area area = areaBiz.findModel(StringConverters.ToLong(id));
        modelAndView.addObject("area",area);
        modelAndView.setViewName("pages/admin/area/areaEdit");

        return modelAndView;
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeAreaEdit")
    @ResponseBody
    public ResultDto executeAreaEdit(Area area,HttpServletRequest request,
                                     @RequestParam(value = "selectParentId[]", required = false) List<String> selectParentIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if (areaBiz.existArea(area,enterprise.getId())) {
            return ResultUtil.error("您输入的区域名称/代码为空或已存在，请重新输入");
        }
        boolean isRootArea = false;
        if(CollectionUtils.isNotEmpty(selectParentIds)){
            if(area.getId()!=null&&area.getId().equals(StringConverters.ToLong(selectParentIds.get(0)))){
                return ResultUtil.error("您不能设置自己为上级，请重新输入");
            }
            Area parentArea = areaBiz.findModel(StringConverters.ToLong(selectParentIds.get(0)));
            if(parentArea!=null){
                //先判断是否存在悖论关系
                if(area.getId()!=null&&StringUtils.isNotBlank(parentArea.getParentIds())&&parentArea.getParentIds().contains(area.getId()+"")){
                    return ResultUtil.error("您不能设置此上级类型，请重新输入");
                }
                area.setParentId(parentArea.getId());
                area.setRootId(parentArea.getRootId());
                area.setLvl((parentArea.getLvl()!=null?parentArea.getLvl():0)+1);
                area.setParentIds((StringUtils.isEmpty(parentArea.getParentIds())?"":(parentArea.getParentIds()+","))+parentArea.getId());
            }else{
                area.setLvl(0);
                area.setParentIds("");
                isRootArea = true;
            }
        }else{
            area.setLvl(0);
            area.setParentIds("");
            isRootArea = true;
        }
        area.setEnterprise(enterprise);
        area.setSystemUserId(systemUser.getId());
        area.setSystemUserName(systemUser.getUserName());
        areaBiz.addOrUpdate(area);
        if(isRootArea){
            area.setRootId(area.getId());
            areaBiz.addOrUpdate(area);
        }
        //如果是变更上级 则整个下级团队都需要变更parentIds 以及 层级字段 以及 rootId字段
        areaBiz.recursionChangeParentIds(area.getId());
        return ResultUtil.success();
    }

    /**
     * 获取系统模块选择数据
     *
     * @param id
     * @param q
     * @return
     */
    @RequestMapping("/getAreaSelect")
    @ResponseBody
    public List<SelectVO> getAreaSelect(@RequestParam(value = "q", required = false) String q,
                                        @RequestParam(value = "id", required = false) String id,
                                        HttpServletRequest request) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        Area area = areaBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&area!=null){
            index = id;
        }
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam("-1", "-1");
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        List<Area> areaList = areaBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(areaList)){
            for(Area area1 : areaList){
                if(StringUtils.isNotBlank(index)&&index.equals(area1.getId()+"")){
                    status = true;
                }
                selectVOS.add(new SelectVO(area1.getAreaName(), area1.getId() + ""));
            }
        }
        if(!status&&area!=null){
            selectVOS.add(new SelectVO(area.getAreaName(), area.getId() + ""));
        }
        return selectVOS;
    }
}
